'''
Created on 2012-9-6

@author: Administrator
'''
import time

from google.appengine.ext import db
from common.util import Logger

_QUINTUS_USERNAME = 'zhouyuding1990@gmail.com'
_QUINTUS_PASSWORD = 'Zz44569565'

logger = Logger()

class User( db.Model ):
    username = db.StringProperty()
    nickname = db.StringProperty()
    password = db.StringProperty()
    about = db.StringProperty()
    email = db.StringProperty()
    website = db.StringProperty()
    avatar = db.BlobProperty()
    
class Comment( db.Model ):
    user = db.ReferenceProperty( reference_class = User )
    text = db.StringProperty()
    time = db.DateTimeProperty( auto_now = True )
    reference = db.SelfReferenceProperty( verbose_name = "reference" )
    #referened = db.ReferenceProperty()

class Blog( db.Model ):
    user = db.ReferenceProperty( reference_class = User )
    title = db.StringProperty()
    catelog = db.StringProperty()
    text = db.StringProperty()
    time = db.DateTimeProperty( auto_now = True )
    picture = db.StringProperty()#this is key of life which this picture belongs to
    #attached picture uri

class BlogComment( db.Model ):
    user = db.ReferenceProperty( reference_class = User )
    blog = db.ReferenceProperty( reference_class = Blog )
    reference = db.SelfReferenceProperty( verbose_name = "reference" )
    #referenced = db.SelfReferenceProperty( verbose_name = "referenced" )
    text = db.StringProperty()
    time = db.DateTimeProperty( auto_now = True )   

class ContactRequest( db.Model ):
    name = db.StringProperty()
    email = db.StringProperty()
    mircroblog = db.StringProperty()
    comments = db.StringProperty()
    time = db.DateTimeProperty( auto_now = True )

class Life( db.Model ):
    #now, the life model only support picture exhibition,and the picture will be stored as its URL link string.
    user = db.ReferenceProperty( reference_class = User )
    picture = db.StringProperty()
    time = db.DateTimeProperty( auto_now = True )
    pictureblob = db.BlobProperty()
    pictureoriginal = db.BlobProperty()
    comment = db.StringProperty()
    
def get_tuple_by_key( model, limit = 30, offset = 0, **dict_ ):
    '''
        get tuple by given arguments, if there is "order by" class, the "order by" key-value pair must be the 
        last argument.
    '''
    logger.log_submodel( "get_tuple_by_key()" )
    query = db.Query( model )
    for key in dict_:
        if key == 'orderby':
            query.order( '-' + dict_[key] )
            logger.log_submodel( "get_tuple_by_key()", "order by -> " + dict_[key] )
        elif key == 'reverse':
            continue
        else :
            query.filter( key + " =", dict_[key] )
            logger.info( "get tuple by key, filter : " + str( key ) + " = " + str( dict_[key] ) )
    '''
    try:
        if dict_['reverse'] == 'True' or dict_['reverse'] == 'true': 
            return query.fetch( limit , offset ).reverse()
        db.Query.fetch(1)
    except:
        pass
    return query.fetch( limit , offset )
    '''
    return query.fetch(limit, offset)
        
    

def delete_record_by_key( model, limite = 30, offset = 0, **dict_ ):
    logger.log_submodel( "delete_record_by_key()" )
    try:
        results = get_tuple_by_key( model, limite, offset, **dict_ )
        for result in results:
            result.delete()
            logger.info( "delete record by key : " + str( result ) )
        return True
    except Exception, e:
        logger.info( "delete record by key : " + e.__class__ + " : " + e.message )

def get_by_pk( model, key_code ):
    logger.log_submodel( "get_by_pk()" )
    if not isinstance( key_code, db.Key ):
        key_code = db.Key( key_code )
    elif isinstance( key_code, db.Key ):
        pass
    else:
        raise Exception( "models.get_by_pk doesn't accept argument except str or db.Key" )
    result = db.Query( model ).filter( "__key__ =", key_code ).get()
    if result :
        logger.info( "success!" )
        return result
    else:
        logger.info( "failed!" )

def delete_by_pk( model, key_code ):
    logger.log_submodel( "delete_by_pk()" )
    result = get_by_pk( model, key_code ) 
    if result:
        result.delete()
        logger.info( "success!" )
        return True
    else:
        logger.info( "failed!" )
        return False
    
def check_for_exist( model, **dict_ ):
    if len( get_tuple_by_key( model, 1, 0, **dict_ ) ) > 0:
        return True
    return False
    
def get_all_blog_list_bundle_by_time():                
    blogs = get_tuple_by_key( Blog, 30, 0, orderby = 'time' )
    time_bundle = []
    temp_list_ = []
    flag_month_year = "";
    '''
        time_bundle is a dict, key is (year,month), value is a list which contains dicts of contains blogs.
        {
            (2012,1):[{time:xxx,title:blog1,catelog:xxx},{time:xxx,title:blog2,catelog:xxx}],
            (2012,7):[{time:xxx,title:blog3,catelog:xxx},{time:xxx,title:blog4,catelog:xxx}]
        }
    '''
    for blog in blogs:
        temp_month = str( blog.time.month )
        temp_year = str( blog.time.year )
        
        if flag_month_year != ( temp_year + temp_month ) and len( temp_list_ ) != 0:
            # if temporary list size > 0 and next year-month != previous one, 
            # 1.copy the temp_list_ into time_bundle list, and clear temporary list
            # 2.set flag_month_year = current year-month
            import copy
            time_bundle.append( copy.copy( temp_list_ ) )
            temp_list_ = []
            temp_list_.append( {'time':blog.time, 'title':blog.title, 'catelog':blog.catelog} )
            flag_month_year = temp_year + temp_month
        else:
            temp_list_.append( {'time':blog.time, 'title':blog.title, 'catelog':blog.catelog} )
            flag_month_year = temp_year + temp_month
    time_bundle.append( temp_list_ )
    return time_bundle 
  
def get_last_news( user ):
    '''
        now, the last new just support blog and life functionalities.
    '''
    query_blog = db.Query( Blog ).filter( 'user', user.key() ).order( '-time' ).fetch( 1, 0 )
    query_life = db.Query( Life ).filter( 'user', user.key() ).order( '-time' ).fetch( 1, 0 )
    if len( query_blog ) > 0 and len( query_life ) > 0:
        if query_life[0].time >= query_blog[0].time:
            return query_life[0]
        else:
            return query_blog[0]
    elif len( query_blog ) == 0 and len( query_life ) == 0:
            pass
    elif len( query_blog ) > 0:
        return query_blog[0]
    else:
        return query_life[0]
    
query = db.Query( User ).filter( 'username =', _QUINTUS_USERNAME ).filter( 'password =', _QUINTUS_PASSWORD )
result = query.fetch( 2 )
if len( result ) > 0:
    logger.info( "quintus exsits." )
    pass
else:
    User( username = _QUINTUS_USERNAME, password = _QUINTUS_PASSWORD ).put()
    logger.info( "put quintus into datastore." )

